package com.focusai.efairy.ui.activity.crop;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.os.Bundle;
import android.widget.Toast;

import com.focusai.efairy.R;
import com.focusai.efairy.ui.widget.CropView;
import com.focusai.efairy.utils.Constants;
import com.focusai.efairy.utils.DateUtils;
import com.focusai.efairy.utils.IOUtil;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.lang.ref.SoftReference;

/**
 * @author Ives
 * @description
 **/
public class CropImageActivity extends Activity {

    private CropView cropView;
    private String cropDir;

    private Bitmap bm = null;

    private static final long MAX_SIZE = 5 * 1024 * 1024;//图片最大5M

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_crop);
        initView();
        cropView.setFrameSize(getIntent().getIntExtra(Constants.EXTRA_FRAME_WIDTH, getResources().getDisplayMetrics().widthPixels),
                getIntent().getIntExtra(Constants.EXTRA_FRAME_HEIGHT, getResources().getDisplayMetrics().widthPixels));

        setData(cropView);
    }



    private void setData(final CropView cropView) {
        final String pathName = getIntent().getStringExtra(Constants.EXTRA_PATH);
        cropDir = getIntent().getStringExtra(Constants.EXTRA_CROP_DIR);

        new Thread() {

            @Override
            public void run() {
                try {

                    final BitmapFactory.Options options = new BitmapFactory.Options();
                    final int digree = checkOptions(options, pathName);
                    //设置缩放比例
                    calculateSize(options, digree);//这个缩放比例是根据屏幕长宽来的//让图片能够缩放显示到屏幕当中

                    //加载缩小的图片
                    CropImageActivity.this.bm = BitmapFactory.decodeFile(pathName, options);
                    //旋转
                    Matrix m = new Matrix();
                    m.postRotate(digree);

                    final SoftReference<Bitmap> b = new SoftReference<Bitmap>(
                            Bitmap.createBitmap(CropImageActivity.this.bm, 0, 0, CropImageActivity.this.bm.getWidth(), CropImageActivity.this.bm.getHeight(), m, true));

                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            cropView.setImage(b,
                                    (digree == 0 || digree == 180 ? CropImageActivity.this.bm.getHeight() : CropImageActivity.this.bm.getWidth()),
                                    (digree == 0 || digree == 180 ? CropImageActivity.this.bm.getWidth() : CropImageActivity.this.bm.getHeight()));
                        }
                    });
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(CropImageActivity.this, "设置图片失败请重新选择图片", Toast.LENGTH_SHORT).show();
                        }
                    });
                }
            }
        }.start();


    }

    private void calculateSize(Options options, int digree) {

        final int width = getResources().getDisplayMetrics().widthPixels;
        final int height = getResources().getDisplayMetrics().heightPixels;

        //确定缩放比例，长宽至少能显示满
        int imgWidth;
        int imgHeight;
        if (digree == 0 || digree == 180) {
            imgWidth = options.outWidth;
            imgHeight = options.outHeight;
        } else {
            imgWidth = options.outHeight;
            imgHeight = options.outWidth;
        }

        int scale_w = Math.round(imgWidth / (float) width);
        int scale_height = Math.round(imgHeight / (float) height);
        options.inSampleSize = scale_w < scale_height ? scale_w : scale_height;//取最小缩放值
        if (options.inSampleSize == 0) {
            options.inSampleSize = 1;
        }
    }

    /**
     * @param options
     * @param pathName
     * @return digree
     * @throws IOException
     */
    private int checkOptions(Options options, String pathName) throws IOException {
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(pathName, options);
        if ("image/jpeg".equals(options.outMimeType) || "image/tiff".equals(options.outMimeType)) {

            options.inJustDecodeBounds = false;
            //判断旋转角度
            ExifInterface exif = new ExifInterface(pathName);
            if (exif != null) {
                // 读取图片中相机方向信息  
                int ori = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
                        ExifInterface.ORIENTATION_UNDEFINED);
                // 计算旋转角度  
                switch (ori) {
                    case ExifInterface.ORIENTATION_ROTATE_90:
                        return 90;
                    case ExifInterface.ORIENTATION_ROTATE_180:
                        return 180;
                    case ExifInterface.ORIENTATION_ROTATE_270:
                        return 270;
                    default:
                        return 0;
                }
            }
        }
        options.inJustDecodeBounds = false;
        return 0;
    }

    protected void initView() {
        cropView = (CropView) findViewById(R.id.cropView);
        cropView.setOnCropButtonClickListener(new CropView.OnCropButtonClickListener() {

            @Override
            public void onConfirm() {

                //缩小后的图片的私有目录
                String photoPath = cropDir + "/" + DateUtils.getCurrentDateByStyle("yyyyMMddHHmmss") + ".jpg";
                File temp = new File(photoPath);
                File temp_dir = temp.getParentFile();
                if (!temp_dir.exists()) {
                    temp_dir.mkdirs();
                }
                try {
                    temp.createNewFile();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }

                try {
                    //写数据
                    IOUtil.write(cropView.getClipImage(CropImageActivity.this), photoPath);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                File file = new File(photoPath);
                if (file.length() > MAX_SIZE) {
                    Toast.makeText(CropImageActivity.this, "图片大小超过最大限制:5M, 请重新选择图片", Toast.LENGTH_LONG).show();
                    return;
                } else {
                    Intent intent = new Intent();
                    intent.putExtra(Constants.EXTRA_PATH, photoPath);
                    setResult(RESULT_OK, intent);
                    finish();
                }


            }

            @Override
            public void onCancel() {
                finish();
            }
        });
    }

    @Override
    protected void onDestroy() {
        this.cropView.releaseBitmap();
        this.cropView = null;
        super.onDestroy();
    }

}
